package test.netease.version3.chapter3.lesson_3_2_1;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author zhangrui
 * @date 2020-06-03 21:46
 * @since 1.0
 */
public class ClassDoNotLoadRepeat {
    public static void main(String[] args) {

        try {

            //可以找到类
            File file = new File("/Users/zhangrui/idea-workspace-me/ZrTest/target/classes/test/netease/version3/chapter3/lesson_3_2_1");
            //一样可以找到类
            //File file2 = new File("/Users/zhangrui/idea-workspace-me/ZrTest/target/classes");
            //还是一样可以找到类
            //File file3 = new File("/Users/zhangrui");

            URL url = file.toURL();
            System.out.println(url);

            while (true) {

                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});

                Class<?> aClass = urlClassLoader.loadClass("test.netease.version3.chapter3.lesson_3_2_1.HelloService");
                System.out.println("HelloService所使用的类加载器 " + aClass.getClassLoader());
                Object newInstance = aClass.newInstance();
                Object value = aClass.getMethod("test").invoke(newInstance);
                System.out.println("调用test方法得到的返回值为 " + value);

                Thread.sleep(3000L);
                System.out.println();
            }

        } catch (MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
                | InvocationTargetException | InterruptedException e) {
            e.printStackTrace();
        }

    }
}
